package com.lei.study.depth.zkclient;

import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.ZkClient;
import org.I0Itec.zkclient.serialize.SerializableSerializer;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * zk 客户端测试
 * 注册的监听器可反复使用，不需要每次都重新注册一次
 * </p>
 *
 * @author <a href='mailto:17674030991@163.com'/>伍磊
 */
public class ZkClientTest {

    public static void main(String[] args) throws IOException, InterruptedException {
        ZkClient zkClient = new ZkClient("localhost:2181", 10000, 5000, new SerializableSerializer());

        // 创建持久节点
        zkClient.createPersistent("/data", "1".getBytes(StandardCharsets.UTF_8));

        // 订阅数据变更事件
        zkClient.subscribeDataChanges("/data", new IZkDataListener() {
            @Override
            public void handleDataChange(String s, Object o) throws Exception {
                System.out.println("数据变更了: " + s + "," + o);
            }

            @Override
            public void handleDataDeleted(String s) throws Exception {
                System.out.println("数据删除了: " + s);
            }
        });

        // 每隔一秒变更一次
        for (int i = 10; i < 20; i++) {
            TimeUnit.SECONDS.sleep(1);
            zkClient.writeData("/data", i);
        }

        System.in.read();
    }
}
